package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.dtos.LikesBehaviorDto;
import com.heima.behavior.pojos.ApLikesBehavior;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.constants.HotArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.ApThreadLocalUtil;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        //1.参数效验
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.获取登录人信息,判断用户是否登录
        ApUser apUser = ApThreadLocalUtil.getUser();
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //游客身份不能进行以下操作
        if (apUser.getId() == null) {
            return ResponseResult.okResult(405,"游客身份禁止，需进行登录");
        }

        //kafka数据实时记录点赞
        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setArticleId(dto.getArticleId());
        mess.setType(UpdateArticleMess.UpdateArticleType.LIKES);


        //3.判断用户是否点赞，查询redis
        //3.1 获取关注缓存hash类型的key
        String like_hash_key = "USER_LIKES_" + dto.getArticleId();
        //3.3判断是已经点赞：查询关注缓存中的小key是否包含点赞人id
        Boolean hasKey = redisTemplate.opsForHash().hasKey(like_hash_key, apUser.getId() + "");
        //4.用户已点赞，继续执行点赞操作则返回
        if (hasKey && dto.getOperation() == 0) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //4.1用户已点赞，执行取消点赞操作，
        if (hasKey && dto.getOperation() == 1) {
            //4.2 则删除缓存数据
            redisTemplate.opsForHash().delete(like_hash_key, apUser.getId() + "");
            //4.3 删除mongodb中的数据
            mongoTemplate.remove(
                    Query.query(Criteria.where("userId").is(apUser.getId()+"").and("articleId").is(dto.getArticleId()))
            , ApLikesBehavior.class);

            //kafka记录数减一
            mess.setAdd(-1);
            kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(mess));

            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //5.用户未点赞,要执行点赞行为操作
        if (!hasKey && dto.getOperation() == 0) {
            //保存数据到redis中
            redisTemplate.opsForHash().put(like_hash_key,apUser.getId() + "","1");
            //保存数据到mongo中
            ApLikesBehavior apLikesBehavior = new ApLikesBehavior();
            apLikesBehavior.setId(ObjectId.get().toHexString());
            apLikesBehavior.setArticleId(dto.getArticleId());
            apLikesBehavior.setCreatedTime(new Date());
            apLikesBehavior.setUserId(apUser.getId().longValue());
            apLikesBehavior.setType((short) 0);
            mongoTemplate.insert(apLikesBehavior);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
